/**
 * @file sys_tick.c
 * @author Linquan  
 * @brief 系统时钟
 * @version 1.0
 * @date 2024-06-14
 * 
 * @copyright Copyright (c) 2024
 * 
 */

#include "sys_tick.h"
#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
#include <pthread.h>
#include "export.h"

#define TICK_1MS            1000
#define TICK_10MS           10000
#define TICK_50MS           50000
#define TICK_100MS          100000
#define TICK_1S             1000000
#define CURRENT_TICK        TICK_10MS

/* 定时器最大回调函数数量 */ 
#define TIMER_CALLBACK_MAX  8 

/* 回调函数列表 */ 
timer_callback func_table[TIMER_CALLBACK_MAX] = {NULL};  

/* 互斥锁 */ 
pthread_mutex_t mutes = PTHREAD_MUTEX_INITIALIZER;      

/* 秒转换成 微秒*/
const unsigned long us_converter_to_sec = 1000 * 1000;  // 1s == 1000 * 1000 us

/* 系统定时计数器 */ 
static uint64_t sys_time_count = 0;   



static void sys_time_increase()
{
    sys_time_count++;
}

       
/**
 * @brief 系统定时线程
 * 
 * @param arg 
 * @return void* 
 */
void * sys_timer_handle(void *arg)
{
    /* 获取当前时间，用于计算时间差*/
    char* candlt;
    struct timeval current_timer, last_time;
    uint64_t diff_time = 0;

    gettimeofday(&last_time, NULL);

    while (1)
    {   
        /* 1、 获取当前时间 */
        gettimeofday(&current_timer, NULL);
        candlt = ctime(&current_timer.tv_sec);

        /* 2、计算 时间差 */
         diff_time = (current_timer.tv_sec * us_converter_to_sec + current_timer.tv_usec)\
                    - (last_time.tv_sec * us_converter_to_sec + last_time.tv_usec);

        /* 3、当大于CURRENT_TICK，就执行一次 */
        if(diff_time >= CURRENT_TICK)
        {
            last_time = current_timer;

            pthread_mutex_lock(&mutes);

            sys_time_increase();    
            for(int i = 0; i < TIMER_CALLBACK_MAX; i++)
            {
                if(func_table[i] != NULL)
                {
                    func_table[i]();
                }
            }

            pthread_mutex_unlock(&mutes);

           //printf("sys time  now: %s\n", candlt);

        }
      
    }    
    
}


/**
 * @brief 
 * 
 * @param tick 
 */
void sys_timer_init(void *ptr)
{
   pthread_t timer_thread;
    pthread_create(&timer_thread, NULL, sys_timer_handle, NULL);
}
 EXPORT_Lv1_BOARD(sys_timer_init,NULL);


/**
 * @brief 获得系统计时时间
 * 
 * @return uint32_t 
 */
uint32_t  sys_time_get_ms()
{
    return sys_time_count*CURRENT_TICK;
} 



/**
 * @brief 获得系统计时时间
 * 
 * @return uint32_t 
 */
uint32_t  sys_time_get_count()
{
    return sys_time_count;
} 


/**
 * @brief 
 * 
 * @param func 
 * @return uint8_t 
 */
uint8_t sys_timer_callback_add(timer_callback func)
{
    static uint8_t func_count = 0;

    if(func ==NULL){
        return 1;
    }
    if(func_count >= TIMER_CALLBACK_MAX){
        return 2;
    }

    func_table[func_count] = func;
    func_count++;
    return 0;
}





